package leetcode.editor.cn.q1_300.q;

/**
 * @author qidi
 * @date 2021-11-02 16:27:30
 */
class Q0025_ReverseNodesInKGroup {


    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public ListNode reverseKGroup(ListNode head, int k) {
            if (head == null || k <= 1) {
                return head;
            }
            ListNode result = new ListNode(0, head);
            int len = 1;
            while ((head = head.next) != null) {
                len++;
            }
            int limit = len / k * k;
            ListNode prev = result;
            for (int i = 0; i < limit; i += k) {
                ListNode curr = prev.next;
                ListNode next = curr.next;
                for (int j = 1; j < k; ++j) {
                    curr.next = next.next;
                    next.next = prev.next;
                    prev.next = next;
                    next = curr.next;
                }
                prev = curr;
            }
            return result.next;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)


    public static void main(String[] args) {
        Solution solution = new Q0025_ReverseNodesInKGroup().new Solution();
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        ListNode n5 = new ListNode(5);
        n4.next = n5;
        ListNode n6 = new ListNode(6);
        n5.next = n6;

        solution.reverseKGroup(n1, 3);
    }
}